// @ts-ignore
import NProgress from "NProgress";

import menu from "./menu";
import router, { whiteList } from ".";

import { useAppTabsStore } from "@/modules/package/appTabs";
import useRequest from "@/hooks/useRequest";
import appToken from "@/utils/appToken";
import useApp from "@/store/useApp";
import ApiAdmin from "@/api/admin";
import { setAppTabsId } from "@/modules/package/appTabs/js/store";

const handleGuard = async (to: any, from: any) => {
  const store = useApp();

  // 场景：刷新404页面
  if (to.path == "/404" && !to.redirectedFrom) {
    return "/";
  }

  // 1. 白名单
  if (whiteList.includes(to.name as string) || to.path == "/404") return true;

  // 2. 未登录，去登录
  if (!appToken.getToken()) {
    // 未登陆，跳至登陆页面
    return "/login";
  }

  // 3. 获取用户登录信息，注册路由和菜单
  if (store.menus?.length == 0) {
    const { data } = await useRequest(ApiAdmin.adminInfo);
    store.userInfo = data.value;
    setAppTabsId(data.value.id);
    // 拉起菜单数据、并注册路由，
    store.appendRouter([...menu]);
    return to;
  }

  // 根据路由，添加tab
  useAppTabsStore().appendTab(
    to,
    from,
    () =>
      //  白名单、顶级页面 都不生产 NavTab
      !whiteList.includes(to.name as string) && !to.meta.isTopPage
  );
};

router.beforeEach(async (to, from) => {
  NProgress.start();
  const res = await handleGuard(to, from);
  NProgress.done();
  return res;
});
